from helpers import updateInfo
from helpers import CompHelp
import os
from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

class MainPage(webapp.RequestHandler):
    """ Open arena page class """

    def get(self):
        user=users.get_current_user()
        
        # Make sure user is logged in, if not redirect to login page
        if not user:
            self.redirect(users.create_login_url(self.request.uri))
            return
        
        # Load user info from database
        # If user is using app for first time (=his info in not in TrendUsers table)
        # then initialize his info
        current_user=updateInfo.getCurrentUser(user)
        
        if self.request.get('ad')=="1":
            advertise=1
            categoryName="Open Sponsored Arena"
        else:
            advertise=0
            categoryName="Open Arena"
    
        template_values = {
            'maxTitleLength' : updateInfo.maxTitleLength, 
            'current_user_totalamount': current_user.totalamount,
            'current_user_bankamount': current_user.bankamount,
            'current_user_investamount': current_user.totalamount-current_user.bankamount,
            'logusername' : user.nickname().capitalize(),
            'loginurl' : users.create_logout_url("/"),
            'logintext' : 'Sign Out',
            'advertise' : advertise,
            'maxStockLength': updateInfo.maxStockLength,
            'maxInputLength': (updateInfo.maxStockLength*updateInfo.maxWordsPerArenaEntity)+updateInfo.maxWordsPerArenaEntity,
            'categoryName' : categoryName,
            'setHead' : 1,
            'maincontent' : 'account_main.html',
            'headContent' : 'openarena_head.html',
            'account_main_content' : 'openarena_main.html'
            
        }
        path = os.path.join(os.path.dirname(__file__), updateInfo.controllersIndexPath)
        self.response.out.write(template.render(path, template_values))

    def post(self):
 
        # Handle all forms submittions
        user=users.get_current_user()
        # If user is using app for first time (=his info in not in TrendUsers table)
        # then initialize his info
        current_user=updateInfo.getCurrentUser(user)
     

        if (self.request.get('action')=="openarena"):
            if self.request.get('advertise')=="true":
                isAdComp=True
            else:
                isAdComp=False
    
            # Check for valid int competition amount
            try:
                compamount=int(self.request.get('amount'))
                startdate=int(self.request.get('startdate'))
                enddate=int(self.request.get('enddate'))
            except:
                self.redirect('/report?msg=5')
                return
            
            owner = user
            if self.request.get('title'):
                title=self.request.get('title')
            else:
                title="TrendSE Arena"
                
            keywordsList=[]
            emailList=[]
            
            validCounter=0
            chosenRadio=-1
            
            #Check for valid radio button (in case of a non ad competition)
            if not isAdComp:
                # Check for existing users
                emailList=self.request.get('inviteusers').splitlines()
                # Remove duplicates
                emailList=set(emailList)
                try:
                    arenaradio=int(self.request.get('arenaradio'))
                except:
                    self.redirect('/report?msg=6')
                    return
                
            # Build list of keywords
            if self.request.get('option1')!='':
                keywordsList.append(self.request.get('option1'))
                if not isAdComp and arenaradio==0:
                    chosenRadio=validCounter
                validCounter+=1
                    
            if self.request.get('option2')!='':
                keywordsList.append(self.request.get('option2'))
                if not isAdComp and arenaradio==1:
                    chosenRadio=validCounter
                validCounter+=1
                    
            if self.request.get('option3')!='':
                keywordsList.append(self.request.get('option3'))
                if not isAdComp and arenaradio==2:
                    chosenRadio=validCounter
                validCounter+=1
                    
            if self.request.get('option4')!='':
                keywordsList.append(self.request.get('option4'))
                if not isAdComp and arenaradio==3:
                    chosenRadio=validCounter
                validCounter+=1
                    
            if self.request.get('option5')!='':
                keywordsList.append(self.request.get('option5'))
                if not isAdComp and arenaradio==4:
                    chosenRadio=validCounter
                validCounter+=1
                
            # Check if user entered a bet in case of non ad arena    
            if (validCounter<=1 or chosenRadio==-1 and not isAdComp):
                self.redirect('/report?msg=7') 
                return
                
            # Open competition
            competition, password=CompHelp.openComp(compamount, emailList, current_user, startdate, enddate, title, self.request.get('publiccomp'), keywordsList, 1, owner, isAdComp)
    
            if competition==-1:
                self.redirect('/report?msg=8')
                return
            elif competition==-2:
                self.redirect('/report?msg=11')
                return
            elif competition==-3:
                self.redirect('/report?msg=12')
                return
            # If user is not an advertiser,join the competition 
            if not isAdComp:
                if CompHelp.joinCompetition(current_user,competition,1,chosenRadio)!=1:
                    self.redirect('/report?msg=9')
                    return
            elif isAdComp:
                # Deduct real money from advertiser account
                if CompHelp.openAdArena(current_user,compamount)!=1:
                    self.redirect('/report?msg=10')
                    return                
        if isAdComp:
            self.redirect('/advertise')
        else:
            self.redirect('/Competition?id=%s&PKey=%s' % (str(competition.key()),password))
        return
 
application = webapp.WSGIApplication(
                                     [('/openArena', MainPage)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
